package com.revai.engine.basic.service.impl;

import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Service;

import com.revai.engine.basic.service.ClassCacheService;
import com.revai.engine.basic.util.ConstConfig;
import com.revai.engine.basic.util.StrUtils;

@Service
public class ClassCacheServiceImpl implements ClassCacheService {
    // class包缓存
    private Map<String, Class<?>> classCacheMap = new HashMap<>();
    // 根据完整包名获取class

    @Override
    public Class<?> getClass(String fullPath) throws ClassNotFoundException {
        //获取  一个未知或任何类型  的Class对象，在HashMap里获取路径对应的值
        Class<?> clazz = classCacheMap.get(fullPath);
        if (clazz == null) {
            //如果HashMap缓冲区找不到，去加载类，并放到HashMap缓冲区，省略了加载类的步骤
            clazz = Class.forName(fullPath);
            classCacheMap.put(fullPath, clazz);
        }
        //返回这个类
        return clazz;
    }
    // 根据表名获取Model
    @Override
    public Class<?> getModelClass(String tableName) throws ClassNotFoundException {
        String modelName = StrUtils.toClassCamelCase(tableName);
        String fullPath = ConstConfig.BASEPACKAGEMODEL + modelName;
        return getClass(fullPath);
    }
    // 根据表名获取Mapper
    @Override
    public Class<?> getMapperClass(String tableName) throws ClassNotFoundException {
        String modelName = StrUtils.toClassCamelCase(tableName);
        String fullPath = ConstConfig.BASEPACKAGEMAPPER + modelName + "Mapper";
        return getClass(fullPath);
    }
    // 根据表名获取Mapper
    @Override
    public Class<?> getExampleClass(String tableName) throws ClassNotFoundException {
        String modelName = StrUtils.toClassCamelCase(tableName);
        String fullPath = ConstConfig.BASEPACKAGEMODEL + modelName + "Example";
        return getClass(fullPath);
    }
    // 根据表名获取Service
    @Override
    public Class<?> getServiceClass(String tableName) {
        //表名 转换为小驼峰
        String modelName = StrUtils.toClassCamelCase(tableName);
        //组织全路径，cn.loongair.provider.at.service. + 表名 + Service
        String fullPath = ConstConfig.BASEPACKAGESERVICE + modelName + "Service";
        try {
            return getClass(fullPath);
        } catch (ClassNotFoundException e) {
            return null;
        }
    }
}
